<?php
namespace Home\Controller;

use Think\Controller;

class CallbackController extends CommonController
{
    public $data = null;
    // 此key内部调用，模拟支付
    private $key = '270fd093ee8a9bf8ae';

    public function __construct()
    {
        parent::__construct();

        Vendor('Weixinpay.Weixinpay');
        $wxpay  = new \Weixinpay();
        $result = $wxpay->notify();

        if (!$result) {
            echo 'error';
            exit;
        } else {
            $this->data = $result;
        }

        // 日志记录
        file_put_contents(WEB_PATH . '/Uploads/Payment_Callback/' . date('Ymd') . '.txt', print_r($this->data, true), FILE_APPEND);
    }

    public function red()
    {
        $key      = I('get.key', '', 'trim');
        $order_no = I('get.order_no', '', 'trim');
        $total    = I('get.total', 0, 'intval');

        // 支付回调数据
        $data           = $this->data;
        $out_trade_no   = $data['out_trade_no'];
        $total_fee      = $data['total_fee'];
        $transaction_id = $data['transaction_id'];

        // 模拟支付时使用
        if ($key == $this->key) {
            $out_trade_no = $order_no;
            $total_fee    = $total;
        }

        $order = M('red_order')->where(['order_no' => $out_trade_no])->find();
        if (!$order) {
            die("订单不存在");
        }

        // 是否支付成功
        if ($order['is_pay']) {
            die("订单已支付");
        }

        // 订单金额
        if ($order['wx_money'] * 100 != $total_fee) {
            die("订单金额不正确");
        }

        begin();
        $result1 = M('red_order')
            ->where(['order_no' => $out_trade_no])
            ->save([
                'is_pay'         => 1,
                'pay_time'       => CUR_DATETIME,
                'transaction_id' => $transaction_id,
            ]);

        $result2 = D('user', 'Service')->moneyLog($order['user_id'], -$order['balance_money'], '余额支付（剩余部分使用微信支付）');

        $result3 = M('red_bag')->where(['id' => $order['red_id']])->save(['status' => 2]);

        $result = $order['balance_money'] > 0 ? $result1 && $result2 && $result3 : $result1 && $result3;
        if ($result) {
            commit();
            die('订单支付成功');
        } else {
            rollback();
            die('订单支付失败');
        }
    }
}
